package com.dangdang.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;

import com.dangdang.domain.Book;
import com.dangdang.domain.Category;
import com.dangdang.domain.Product;
import com.dangdang.util.HbnUtils;

/**
 * 商品,类别,业务层实现类
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-1-25
 */
public class CatalogServiceImpl implements CatalogService {

	/** 默认排序 */
	public static final int ORDER_DEFAULT = 1;

	/** 按上架时间升序 */
	public static final int ORDER_ADD_TIME_ASC = 2;

	/** 按上架时间降序 */
	public static final int ORDER_ADD_TIME_DESC = 3;

	/** 按书名升序 */
	public static final int ORDER_PRODUCT_NAME_ASC = 4;

	/** 按书名降序 */
	public static final int ORDER_PRODUCT_NAME_DESC = 5;

	/** 存放各种排序查询语句 */
	private final Map<Integer, String> querys = new HashMap<Integer, String>();

	/**
	 * 排序条件
	 * 
	 * @return
	 */
	public Map<Integer, String> getMessageOrderOptions() {
		Map<Integer, String> options = new HashMap<Integer, String>();
		options.put(ORDER_DEFAULT, "默认排序");
		options.put(ORDER_ADD_TIME_ASC, "按上架时间升序");
		options.put(ORDER_ADD_TIME_DESC, "按上架时间降序");
		options.put(ORDER_PRODUCT_NAME_ASC, "按书名升序");
		options.put(ORDER_PRODUCT_NAME_DESC, "按书名降序");
		return options;
	}

	public CatalogServiceImpl() {
		this.initQuerys();
	}

	/**
	 * 排序查询语句
	 */

	private void initQuerys() {
		String sql = "from Product pro "
				+ "join fetch pro.categories cat where cat.id=? ";
		String ody = "order by pro";
		// !!!Warring..在这里使用的每个字段都是Java类的属性
		querys.put(ORDER_DEFAULT, sql);
		querys.put(ORDER_ADD_TIME_ASC, sql + ody + ".addTime asc");
		querys.put(ORDER_ADD_TIME_DESC, sql + ody + ".addTime desc");
		querys.put(ORDER_PRODUCT_NAME_ASC, sql + ody + ".productName asc");
		querys.put(ORDER_PRODUCT_NAME_DESC, sql + ody + ".productName desc");
	}

	/**
	 * 根据类别ID查找类别.<br>
	 * 该方法可以查寻指定ID当前类,也可以查询该指定类的子类类.
	 */
	@SuppressWarnings("unchecked")
	public Category getCategoryById(Integer id, boolean withSub) {
		Session session = HbnUtils.getSession();
		Category cat = null;
		if (withSub) {
			// 联合查寻多级分类
			String hql = "select distinct c from Category c "
					+ "join fetch c.subCategories c1 "
					+ "join fetch c1.subCategories where c.id=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, 1);
			List<Category> list = query.list();
			if (list.size() > 0) {
				cat = list.get(0);
			}
		} else {
			// 只查询该类本身,而不级联子类
			cat = (Category) session.get(Category.class, id);
		}
		session.close();
		return cat;
	}

	/**
	 * 根据商品ID查询该类的所有商品,
	 */
	@SuppressWarnings("unchecked")
	public List<Product> findProductByCategoryId(Integer catId) {
		Session session = HbnUtils.getSession();
		Query query = session
				.createQuery("from Product p join fetch p.categories cat where cat.id=?");
		query.setParameter(0, catId);
		List<Product> list = query.list();
		session.close();
		return list;
	}

	/**
	 * 根据商品ID查询指定的商品
	 * 
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Product findProductById(Integer id) {
		Product product = null;
		Session session = HbnUtils.getSession();
		String hql = "select new Product(p.id,p.productName, p.fixedPrice, p.dangPrice,p.productPic) from Product p where p.id=?";
		Query query = session.createQuery(hql);
		query.setParameter(0, id);
		List list = query.list();
		if (list.size() > 0)
			product = (Product) list.get(0);
		session.close();
		return product;
	}

	/**
	 * 根据父ID查询与该类别同等级的所有类别
	 * 
	 * @param parentId
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Category> findCategoryByParentId(Integer parentId) {
		Session session = HbnUtils.getSession();
		Query query = session.createQuery("from Category where parentId=?");
		query.setParameter(0, parentId);
		List<Category> categories = query.list();
		session.close();
		return categories;
	}

	/**
	 * 排序查看图书<br>
	 * 根据当前类别ID,指定的页数,指定的每页显示的条目数查找 指定的图书
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Product> findProductByCategoryId(Integer catId, Integer page,
			Integer rowsPerPage, Integer order) {
		Session session = HbnUtils.getSession();

		Query query = session.createQuery(querys.get(order));
		query.setParameter(0, catId);

		/** 从第几条结果开始取 */
		query.setFirstResult((page - 1) * rowsPerPage);

		/** 每次取的最大结果条数 */
		query.setMaxResults(rowsPerPage);
		List<Product> list = query.list();
		session.close();
		return list;
	}

	/**
	 * 根据当前类别ID,每页显示的条目书,查看一共需要多少页来显示
	 */
	@Override
	public int getProductTotalPageByCategoryId(Integer catId,
			Integer rowsPerPage) {
		Session session = HbnUtils.getSession();
		Category cat = (Category) session.get(Category.class, catId);
		session.close();

		// 得到该类的商品数量
		int rows = cat.getProductNum();
		// 如果有余的,那这个余数一定小于除数,这里加1就可以将剩余的条目加在最后一页
		if (rows % rowsPerPage == 0) {
			return rows / rowsPerPage;
		} else {
			return rows / rowsPerPage + 1;
		}
	}

	@Override
	public Book findBookById(Integer bookId) {
		Session session = HbnUtils.getSession();
		Book book = (Book) session.get(Book.class, bookId);
		session.close();
		return book;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> findProductByLikeKey(String likeKey) {
		Session session = HbnUtils.getSession();
		Query query = session
				.createQuery("select s.productName from Product s where s.productName like ?");
		query.setParameter(0, likeKey + "%_");
		List<Product> productList = query.list();
		session.close();
		return productList;
	}

	public static void main(String[] args) {
		CatalogServiceImpl cs = new CatalogServiceImpl();
		List<Product> pps = cs.findProductByLikeKey("");
		for (Product p : pps) {
			System.out.println(p.getProductName());
		}
	}

}
